﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using Swsk33.SimpleArcEngine.Dialog;
using System.Collections.Generic;

namespace Swsk33.SimpleArcEngine.Util
{
	/// <summary>
	/// 获取点击缓冲区内城市信息
	/// </summary>
	public class GetCityInBuffer : ICommand, ITool
	{
		/// <summary>
		/// 被操作地图对象
		/// </summary>
		private AxMapControl map;

		public void OnCreate(object Hook)
		{
			map = (AxMapControl)Hook;
		}

		public bool Enabled
		{
			get
			{
				return true;
			}
		}

		public bool Checked
		{
			get
			{
				return true;
			}
		}

		public string Name
		{
			get;
			set;
		}

		public string Caption
		{
			get;
			set;
		}

		public string Tooltip
		{
			get;
			set;
		}

		public string Message
		{
			get;
			set;
		}

		public string HelpFile
		{
			get;
			set;
		}

		public int HelpContextID
		{
			get;
			set;
		}

		public int Bitmap
		{
			get;
			set;
		}

		public string Category
		{
			get;
			set;
		}

		public void OnClick()
		{

		}

		public void OnMouseDown(int button, int shift, int x, int y)
		{
			// 获取鼠标在地图上点的点
			IGeometry point = map.ToMapPoint(x, y);
			// 以该点新建拓扑处理器
			ITopologicalOperator pointOperator = (ITopologicalOperator)point;
			pointOperator.Simplify();
			// 以该点建立一个缓冲区
			IGeometry selectBuffer = pointOperator.Buffer(8);
			// 新建查询器
			ISpatialFilter filter = new SpatialFilter();
			// 设定查询范围为全部字段
			filter.SubFields = "*";
			// 设定查询的几何的范围为我们缓冲区范围
			filter.Geometry = selectBuffer;
			// 查询Shape
			filter.GeometryField = "shape";
			// 查询相交于缓冲区的要素
			filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
			IFeatureLayer layer = null;
			for (int i = 0; i < map.LayerCount; i++)
			{
				layer = (IFeatureLayer)map.get_Layer(i);
				if (layer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPoint)
				{
					continue;
				}
				if (layer.Name == "cities")
				{
					break;
				}
			}
			IFeatureCursor cursor = layer.Search(filter, false);
			List<IFeature> result = new List<IFeature>();
			IFeature feature;
			while ((feature = cursor.NextFeature()) != null)
			{
				result.Add(feature);
			}
			double[] location = { ((IPoint)point).X, ((IPoint)point).Y };
			new CityTreeView(map, layer.FeatureClass, result, location).ShowCityTreeViewDialog();
		}

		public void OnMouseMove(int button, int shift, int x, int y)
		{

		}

		public void OnMouseUp(int button, int shift, int x, int y)
		{

		}

		public void OnDblClick()
		{

		}

		public void OnKeyDown(int keyCode, int shift)
		{

		}

		public void OnKeyUp(int keyCode, int shift)
		{

		}

		public bool OnContextMenu(int x, int y)
		{
			return true;
		}

		public void Refresh(int hdc)
		{

		}

		public bool Deactivate()
		{
			return true;
		}

		public int Cursor
		{
			get;
			set;
		}
	}
}